package com.starblink.post.detail.adapter

import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.postDelayed
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.user.UserRelationCodeEnum
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.util.post.PostUtils
import com.starblink.android.common.R
import com.starblink.android.common.utils.PostDetailHelp
import com.starblink.android.common.view.decoration.SpaceItemDecoration
import com.starblink.basic.autosize.utils.AutoSizeUtils.dp2px
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.view.indicator.GuangDrawableIndicator
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.ScreenUtils
import com.starblink.comment.ui.CommentPostListDialog
import com.starblink.feedback.ui.PostMoreDialog
import com.starblink.novice_guide.SkNoviceGuideColl
import com.starblink.post.databinding.ItemPostDetailBinding
import com.starblink.product.databinding.ItemMountProductBinding
import com.starblink.product.view.MountedProductHolder
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.fragment.Poster
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import com.youth.banner.listener.OnPageChangeListener


class PostDetailHolder(
    binding: ItemPostDetailBinding,
    val activity: FragmentActivity, val traceId: String?,
    val shareCallBack: () -> Unit,
    val pageTrackTag: String, val isFromFeeds: Boolean = false,
) :
    BaseBindingVH<PostD, ItemPostDetailBinding>(binding = binding) {

    var currentImgUrl: String? = ""//当前展示图片 用于识图
    var hasShowed: Boolean = false//是否已初始化过
    override fun onBind(post: PostD, position: Int) {
        currentImgUrl = post.mainPic
        setLayoutSize(post, position)

        showLikeCommentView(
            activity, post, binding.tvComment, binding.tvShare, binding.tvLike,
            binding.ivComment, binding.ivLike, position
        )

        PostDetailHelp.showPostUser(activity, post.posterInfo, binding.ivUser, binding.tvName)

        setFollowState(post.posterInfo.poster.relationCode)

        PostDetailHelp.showTopicView(activity, post.operatorHashtagList, binding.flTopic)

        ///内容标题+用户话题
        if (post.content != null) {
            binding.tvTitle.visibility = View.VISIBLE
            val accountHashtagList: List<PostD.AccountHashtagList?> =
                post.accountHashtagList ?: listOf()

            Log.i("PostDetailHolder", "===00=${post.content}=========$accountHashtagList")

            val viewWidth: Int = ScreenUtils.getScreenWidth(activity) - dp2px(activity, 48f)
            binding.tvTitle.initWidth(viewWidth)
            binding.tvTitle.maxLines = 4
            binding.tvTitle.setHasAnimation(true)
            binding.tvTitle.setCloseInNewLine(false)
            binding.tvTitle.setOpenSuffixColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray400))
            binding.tvTitle.setCloseSuffixColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray400))
            val topicChar =
                binding.tvTitle.replaceTopicSpan(
                    accountHashtagList,
                    post.content, com.starblink.basic.style.R.color.sk_gray500
                ) { ///跳转去hashtag详情
                        name, id ->
                    activity.navigationTo(RoutePage.Post.PAGE_HASHTAG) {
                        withString(RoutePage.Post.TOPIC_ID, id)
                    }
                }
            binding.tvTitle.setOriginalText(
                topicChar
            )
        } else {
            binding.tvTitle.visibility = View.GONE
        }

        showMountedProduct(post, binding.llProduct, binding.recycler)

        setListener(post, position)

        if (position == 0) {
            if (!hasShowed) {
                hasShowed = true
                Log.e("ProductDetailCardView", "==1===$position==${post.id}")
                itemView.trackData(
                    page = SpmPageDef.DetailRoute,
                    element = SpmElementDef.DetailContent,
                    traceInfo = post.traceInfo,
                    params = SpmTrackHandler.trackPostMap(
                        position,
                        post,
                        traceId = if (position == 0) (traceId ?: "") else ""
                    ),
                    showRatio = 0.6f,
                    businessSuffixID = businessSuffixId(post)
                )
            }
        } else {
            Log.e("ProductDetailCardView", "=====$position==${post.id}")
            itemView.trackData(
                page = SpmPageDef.DetailRoute,
                element = SpmElementDef.DetailContent,
                traceInfo = post.traceInfo,
                params = SpmTrackHandler.trackPostMap(
                    position,
                    post,
                    traceId = if (position == 0) (traceId ?: "") else ""
                ),
                showRatio = 0.6f,
                businessSuffixID = businessSuffixId(post)
            )
        }
    }

    /**
     * 获取挂载商品
     */
    private fun showMountedProduct(
        post: PostD,
        llProduct: LinearLayout,
        recycler: RecyclerView,
    ) {

        var productList: ArrayList<ProductF> = arrayListOf()//挂载商品

        val mAdapter: MutableAdapter by lazyOnNone {
            MutableAdapter(productList).apply {
                addVhDelegate {
                    MountedProductHolder(
                        ItemMountProductBinding.inflate(it.inflater, it, false), activity
                    )
                }
            }
        }
        if (post.productList != null && post.productList!!.isNotEmpty()) {
            for (item in post.productList!!) {
                productList.add(item.productF)
            }
        }

        llProduct.visibleOrGone(productList.isNotEmpty()) {
            recycler.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

            if (recycler.itemDecorationCount === 0) {
                recycler.addItemDecoration(
                    SpaceItemDecoration.newHorizontalDecoration(CommUtils.dip2px(5))
                )
            }
            recycler.adapter = mAdapter
            mAdapter.notifyDataSetChanged()
        }
    }


    private fun setListener(post: PostD, position: Int) {
        binding.tvFollow.click {//关注
            CommonMutateManage.followUser(
                activity,
                post.posterInfo.poster.id,
                post.posterInfo.poster.relationCode,
                {
                    setFollowState(if (!PostUtils.followed(post.posterInfo.poster.relationCode)) UserRelationCodeEnum.FOLLOW.ordinal else UserRelationCodeEnum.NOTHING.ordinal)
                }) { state ->

                ApolloValSetExt.setApolloVal<Poster>(post.posterInfo.poster, "relationCode", state)
                setFollowState(state)
            }
        }
        binding.tvMore.setOnClickListener {//更多
            PostMoreDialog(
                activity, activity.supportFragmentManager,
                post
            ).show(activity.supportFragmentManager, "more")
        }
        binding.ivShare.setOnClickListener {//分享
            ShareDialog(
                activity,
                "${ShareUrlUtils().getUrl(ShareTypeEnum.PIC_POST)}${post.id}",
                shareCome = ShareTypeEnum.PIC_POST, imageUrl = post.mainPic
            ) {
                shareCallBack.invoke()
//                val count = post.shareCount + 1
//                ApolloValSetExt.setApolloVal<PostD>(post, "shareCount", count)
//                tvShare.text = count.toString()
            }.show(activity.supportFragmentManager, "share")

            AppsflyerManager.reportContentShare(
                mapOf(
                    "af_content_id" to post.id,
                    "af_content_type" to (post.contentType ?: "1"),
                )
            )
        }

        binding.ivImgSearch.run {
            trackData(
                page = SpmPageDef.SingleDetailRoute,
                element = SpmElementDef.ImageRecognition,
                onlyHit = true,
                traceInfo = post.traceInfo,
                params = SpmTrackHandler.trackPostMap(
                    position,
                    post,
                    traceId = if (position == 0) (traceId ?: "") else ""
                )
            )
            click {
                activity.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                    withString(RoutePage.ImageSearch.ARGS_IMG_URL, currentImgUrl)
                    withString(
                        RoutePage.ImageSearch.ARG_POST_PIC_ID,
                        post.pictures?.getOrNull(0)?.pictureF?.id
                    )
                }
            }
        }
    }

    private fun setFollowState(relationCode: Int) {
        if (PostUtils.followed(relationCode)) {
            binding.tvFollow.text =
                CommUtils.getString(com.starblink.basic.style.R.string.following)
            binding.tvFollow.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray400))
        } else {
            binding.tvFollow.text =
                CommUtils.getString(com.starblink.basic.style.R.string.add_follow)
            binding.tvFollow.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray600))
        }
    }

    private fun setLayoutSize(post: PostD, position: Int) {
        binding.banner.run {
            updateLayoutParams<ConstraintLayout.LayoutParams> {
                this.dimensionRatio =
                    if (post.mainPicSize.isNullOrEmpty()) "1" else post.mainPicSize?.let {
                        var ratio = 1f
                        try {
                            ratio = it.split("*").let { list ->
                                list[0].toFloat() / list[1].toFloat()
                            }
                        } catch (e: Exception) {
//                            SKLogger.e(ProductCardView.TAG, e.message ?: "mainPicSize parse erro")
                        }
                        ratio.toString()
                    }
                if (position == 0 && binding.ivImgSearch.isVisible) {
                    binding.ivImgSearch.postDelayed(delayInMillis = 500) {
                        SkNoviceGuideColl.handlePostImgSearch(
                            activity,
                            binding.ivImgSearch,
                            binding.root,
                        ) {
                            navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {

                                if (post.pictures?.isNotEmpty() == true) {
                                    withString(
                                        RoutePage.ImageSearch.ARGS_IMG_URL,
                                        post.pictures!![0].pictureF.picUrl
                                    )
                                    withString(
                                        RoutePage.ImageSearch.ARG_POST_PIC_ID,
                                        post.pictures!![0].pictureF.id
                                    )
                                } else {
                                    withString(RoutePage.ImageSearch.ARGS_IMG_URL, post.mainPic)
                                }

                            }
                        }
                    }
                }
            }

            setAdapter(
                PostImageAdapter(post.pictures, context, {
                    context.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                        withString(RoutePage.ImageSearch.ARGS_IMG_URL, it.pictureF.picUrl)
                        withString(RoutePage.ImageSearch.ARG_POST_PIC_ID, it.pictureF.id)
                    }
                }, { url, iv ->
                })
            ).addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int,
                ) {
                }

                override fun onPageSelected(pos: Int) {
                    if (post.pictures?.size ?: 0 > pos) {
                        currentImgUrl = post.pictures?.get(pos)?.pictureF?.picUrl
                    }
                    Log.e(
                        "onPageSelected",
                        "=====${post.pictures?.get(pos)?.pictureF?.imageIdentifyFlag}"
                    )
                    binding.ivImgSearch.visibleOrGone(post.pictures?.get(pos)?.pictureF?.imageIdentifyFlag == true) {}
                    binding.ivImgSearch.click {
                        activity.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                            withString(RoutePage.ImageSearch.ARGS_IMG_URL, currentImgUrl)
                            withString(
                                RoutePage.ImageSearch.ARG_POST_PIC_ID,
                                post.pictures?.getOrNull(pos)?.pictureF?.id
                            )
                        }
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
                .setIndicatorSpace(dp2px(6f))
                .setIndicator(
                    GuangDrawableIndicator(
                        activity,
                    )
                )
        }
    }

    /**
     * 点赞 评论 分享等信息
     */
    fun showLikeCommentView(
        activity: FragmentActivity,
        post: PostD,
        tvComment: TextView,
        tvShare: TextView,
        tvLike: TextView,
        ivComment: ImageView,
        ivLike: ImageView,
        position: Int,
    ) {
        tvComment.text = if (post.commentCount == 0) "" else post.commentCount.toString()
        tvShare.text = if (post.shareCount == 0) "" else post.shareCount.toString()

        if (post.liked) {
            ivLike.setImageResource(R.mipmap.detail_like)
        } else {
            ivLike.setImageResource(R.mipmap.detail_unlike)
        }
        tvLike.text = if (post.likeNumbers == 0) "" else post.likeNumbers.toString()


        ivLike.run {
            trackData(
                page = SpmPageDef.SingleDetailRoute,
                onlyHit = true,
                traceInfo = post.traceInfo,
                element = SpmElementDef.postDetailLike,
                params = SpmTrackHandler.trackPostMap(
                    position,
                    post,
                    traceId = if (position == 0) (traceId ?: "") else ""
                )
                    .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                    .plus("result" to if (post.liked) "0" else "1")
            )
            click {//点赞
                CommonMutateManage.likePost(
                    activity,
                    post.id,
                    post.contentType,
                    post.posterInfo.poster.id,
                    post.liked,
                    post.likeNumbers,
                    {
                        PostDetailHelp.changeLikeState(
                            !post.liked,
                            if (!post.liked) post.likeNumbers + 1 else post.likeNumbers - 1,
                            ivLike, tvLike
                        )
                    }) { like, count ->
                    ApolloValSetExt.setApolloVal<PostD>(post, "liked", like)
                    ApolloValSetExt.setApolloVal<PostD>(post, "likeNumbers", count)
                    this.trackData(
                        page = SpmPageDef.SingleDetailRoute,
                        onlyHit = true,
                        traceInfo = post.traceInfo,
                        element = SpmElementDef.postDetailLike,
                        params = SpmTrackHandler.trackPostMap(
                            position,
                            post,
                            traceId = if (position == 0) (traceId ?: "") else ""
                        )
                            .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                            .plus("result" to if (post.liked) "0" else "1")
                    )
                    PostDetailHelp.changeLikeState(
                        like, count,
                        ivLike, tvLike
                    )
                }
            }
            ivComment.click {//评论
                CommentPostListDialog(
                    activity,
                    post.id,
                    post.contentType ?: "1",
                    post.commentCount
                ) {
                    ApolloValSetExt.setApolloVal<PostD>(post, "commentCount", post.commentCount + 1)
                    tvComment.text = post.commentCount.toString()
                }.show(activity.supportFragmentManager, "comment")
            }
        }
    }

}